package com.ruoyi.common.core.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: zqs-mall
 * @description: 自定义校验器
 * @author: Mr.Zhang
 * @create: 2022-06-02 16:40
 **/
public class StatusConstraintValidator implements ConstraintValidator<Status, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * 初始化方法
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(Status constraintAnnotation) {
        int[] values = constraintAnnotation.value();
        for (int i = 0; i < values.length; i++) {
            set.add(values[i]);
        }

        ConstraintValidator.super.initialize(constraintAnnotation);

    }

    /**
     * 判断是否校验成功
     *
     * @param value   需要校验的值
     * @param context context in which the constraint is evaluated
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}
